package com.itheima.service.Impl;


import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.SimpleTimeZone;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	/**
	 * 根据用户名查询用户详细信息
	 * 此方法用于从数据库中加载用户信息，包括用户名、密码和权限
	 * 如果用户不存在，则抛出UsernameNotFoundException异常
	 *
	 * @param username 用户名，用于查询用户信息
	 * @return UserDetails对象，包含用户详细信息
	 * @throws UsernameNotFoundException 如果用户不存在，则抛出此异常
	 */
	@Override
	public UserDetails findByUsername(String username) throws UsernameNotFoundException {
		// 通过用户名从数据库中获取用户信息
		User user = userMapper.getByUsername(username);
		// 如果用户信息为空，抛出异常
		if (user == null) {
			throw new UsernameNotFoundException("用户名不存在");
		}
		// 获取用户ID
		Integer userId = user.getId();
		// 通过用户ID从数据库中获取用户权限列表
		List<String> authorities = userMapper.getAuthoritirByUserId(userId);
		// 创建一个列表存储转换后的权限信息
		List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();
		// 遍历权限列表，将每个权限转换为SimpleGrantedAuthority对象并添加到列表中
		for (String authority : authorities) {
			grantedAuthorities.add(new SimpleGrantedAuthority(authority));
		}
		// 返回包含用户名、密码和权限的UserDetails对象
		return new org.springframework.security.core.userdetails.User(username, user.getPassword(), grantedAuthorities);
	}
}
